package org.zjz.basket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.zjz.basket.dto.LoginFormDTO;
import org.zjz.basket.dto.UserInfoDTO;
import org.zjz.basket.entity.UserEntity;
import org.zjz.basket.enums.JwtBodyKeyEnum;
import org.zjz.basket.global.CommonException;
import org.zjz.basket.mapper.UserMapper;
import org.zjz.basket.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.zjz.basket.util.JwtUtils;
import org.zjz.basket.util.RequestUtils;

import java.util.Collections;
import java.util.Optional;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zjz
 * @since 05/07/2022 - 11:57 下午
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
    @Autowired
    private JwtUtils jwtUtils;

    @Value("${fairy.jwt.iss}")
    private String iss;

    @Value("${fairy.jwt.ttl}")
    private long ttl;

    @Override
    public String login(LoginFormDTO dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        UserEntity userEntity = this.getOne(new QueryWrapper<UserEntity>()
                .eq(UserEntity.U_USERNAME, username).eq(UserEntity.U_PASSWORD, password));
        Optional.ofNullable(userEntity).orElseThrow(() -> new CommonException("login fail"));
        return jwtUtils.createJwt(iss, "login", username, ttl, Collections.emptyMap());
    }

    @Override
    public UserInfoDTO info() {
        String username = getUsernameFromRequest();
        UserEntity entity = this.getOne(new QueryWrapper<UserEntity>().eq(UserEntity.U_USERNAME, username));
        return new UserInfoDTO().setName(username)
                .setRoles(Collections.singletonList(entity.getIdentity()))
                .setAvatar(entity.getPicture())
                .setIntro(entity.getRealName());
    }

    @Override
    public String getUsernameFromRequest() {
        return jwtUtils.getBodyValue(RequestUtils.getHeaderValue("Authorization"), JwtBodyKeyEnum.AUD);
    }
}
